package com.konsung.ksdc.common.mqtt.parser;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.stmt.QueryBuilder;
import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.MqttMsgBean;
import com.konsung.ksdc.bean.MqttMsgNotice;
import com.konsung.ksdc.bean.netbean.RegisterUserNetBean;
import com.konsung.ksdc.common.database.DatabaseHelper;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.BroadCastActions;
import com.konsung.ksdc.common.utils.DateUtils;
import com.konsung.ksdc.config.MyApplication;
import com.konsung.ksdc.config.NetConfig;

import java.util.List;

import okhttp3.Call;

/**
 * 好友验证通过消息处理器
 * Created by andy on 2017/4/19.
 */
public class RequestPassedMessageHandler extends MqttMessageHandler {

    @Override
    public byte[] parseMessage(MqttMsgBean bean) throws Exception {
        throw new Exception("illegal operation!");
    }

    @Override
    public MqttMsgBean parseMessage(String topicName, byte[] bytesContent) throws Exception {
        MqttMsgBean bean = fillMsgBeanHeader(topicName, bytesContent);
        bean.setMsgContent("");
        return bean;
    }

    @Override
    public void writeNotice(String topicName, String isRead, MqttMsgBean msg) throws Exception {
        long timestamp = 0;
        try {
            timestamp = DateUtils.getDateFormat(msg.getMsgSendDate(),
                    DateUtils.yyyyMMddHHmmss).getTime();
        } catch (Exception e) {
            e.printStackTrace();
        }

        MqttMsgNotice notice = new MqttMsgNotice();
        notice.setTopicName(topicName);
        notice.setIsRead(isRead);
        notice.setTargetType(msg.getMsgTargetType());
        notice.setLastPublishUsrId(msg.getContact());
        notice.setTimestamp(timestamp);
        notice.setOwnerUserId(NetConfig.currentUser.getUserId());
        // 最多显示12个长度的字符
        notice.setNoticeMsg(MyApplication.getContext().getString(R.string
                .contact_request_passed));

        Dao dao = DatabaseHelper.getHelper(MyApplication.getContext()).getDao(MqttMsgNotice.class);
        dao.createOrUpdate(notice);
    }

    @Override
    public void hanlderReceivedMessage(String topicName, byte[] datas) throws Exception {
        MqttMsgBean msg = this.parseMessage(topicName, datas);
        onContactRequestPassed(msg);
    }

    /**
     * 好友验证通过后，进行相关处理
     * @param msgBean 消息对象
     */
    public void onContactRequestPassed(final MqttMsgBean msgBean) {
        RequestUtils.findUserById(msgBean.getContact(), new RequestCallback() {
            @Override
            public void onError(Call call, Exception e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(ResponseBean responseBean) {
                RegisterUserNetBean user = responseBean.getEntity(RegisterUserNetBean.class);
                try {
                    saveContactToDb(user, msgBean);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 初始化联系人列表
     * @param contactBean 联系人bean
     * @param msgBean 消息bean
     * @throws Exception Exception
     */
    public void saveContactToDb(RegisterUserNetBean contactBean, MqttMsgBean
            msgBean) throws Exception {
        contactBean.setOwnerId(NetConfig.currentUser.getUserId());

        RuntimeExceptionDao dao = DatabaseHelper
                .getHelper(MyApplication.getContext())
                .getRuntimeExceptionDao(RegisterUserNetBean.class);

        QueryBuilder qb = dao.queryBuilder();
        qb.where().eq("userId", contactBean.getUserId()).and()
                .eq("ownerId", NetConfig.currentUser.getUserId());

        List<RegisterUserNetBean> contact = dao.query(qb.prepare());
        if (!contact.isEmpty()) {
            dao.delete(contact);
        }

        dao.create(contactBean);

        writeNotice(msgBean.getContact(), "N", msgBean);
        sendBroadcast(msgBean, BroadCastActions.ACTION_REQUEST_PASSED);
        playSound();
    }
}
